package net.chasing.androidbaseconfig.widget.view_pager;

import android.app.Activity;
import android.content.Context;
import androidx.viewpager.widget.ViewPager;
import android.view.animation.Interpolator;
import android.widget.Scroller;

import net.chasing.androidbaseconfig.util.GenericTools;

import java.lang.reflect.Field;

/**
 * 设置ViewPager的通过点击tab时页面切换速度为0
 * 而进行滑动切换的速度不变
 */
public class FixedSpeedScroller extends Scroller {
    private int mScreenWidth;

    public FixedSpeedScroller(Activity activity) {
        super(activity);
        mScreenWidth = GenericTools.getScreenWidth(activity);
    }

    public FixedSpeedScroller(Context context, Interpolator interpolator) {
        super(context, interpolator);
    }

    public FixedSpeedScroller(Context context, Interpolator interpolator, boolean flywheel) {
        super(context, interpolator, flywheel);
    }

    @Override
    public void startScroll(int startX, int startY, int dx, int dy, int duration) {
        if (Math.abs(dx) >= mScreenWidth) { //通过点击标题栏切换一页及以上就忽略过渡动画进行直接展示
            super.startScroll(startX, startY, dx, dy, 0);
        } else { //正常通过左右滑动则保留原动画过渡
            super.startScroll(startX, startY, dx, dy, duration);
        }
    }

    @Override
    public void startScroll(int startX, int startY, int dx, int dy) {
        startScroll(startX, startY, dx, dy, 300);
    }

    // 进行设置
    public static void bind(Activity activity, ViewPager viewPager){
        try {
            //设置ViewPager的页面切换速度为0，避免间隔较大的页面跳转产生问题
            Field mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(activity);
            mScroller.set(viewPager, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}